# ui_qt.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel
import ctypes

# 加载核心逻辑库
core_lib = ctypes.CDLL('./libcore.so')

# 设置函数原型
core_lib.core_init.argtypes = [ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_char_p)]
core_lib.core_handle_event.argtypes = [ctypes.c_char_p, ctypes.c_char_p]

class QtUI:
    def __init__(self):
        self.app = QApplication([])
        self.window = QWidget()
        self.window.setGeometry(100, 100, 300, 200)
        
        # 创建UI元素
        self.button = QPushButton('Click Me', self.window)
        self.button.setGeometry(10, 10, 120, 50)
        self.button.clicked.connect(self.on_button_click)
        
        self.status_label = QLabel('Initializing...', self.window)
        self.status_label.setGeometry(10, 70, 280, 30)
        
        # 初始化核心逻辑
        self.state_callback = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_char_p)(self.update_state)
        core_lib.core_init(self.state_callback)
    
    def on_button_click(self):
        # 向核心逻辑发送事件
        core_lib.core_handle_event(b"button_click", b"main_button")
    
    def update_state(self, key, value):
        # 从核心逻辑接收状态更新
        status = ctypes.string_at(value).decode('utf-8')
        self.status_label.setText(f"Status: {status}")
    
    def run(self):
        self.window.show()
        self.app.exec_()

def main():
    app = QApplication(sys.argv)
    window = QtUI()
    window.run()
    sys.exit(app.exec_())

# 程序入口
if __name__ == "__main__":
    main()